package shardingsphere.demo.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import shardingsphere.demo.data.Tenant;

import java.io.StringReader;
import java.sql.Connection;
import java.util.Properties;

@Intercepts({@Signature(method = "prepare", type = StatementHandler.class, args = {Connection.class, Integer.class})})
public class MybatisDataInterceptor implements Interceptor
{
    @Override
    public Object intercept(Invocation invocation)
        throws Throwable
    {
        StatementHandler handler = (StatementHandler) invocation.getTarget();

        //由于mappedStatement中有我们需要的方法id,但却是protected的，所以要通过反射获取
        MetaObject statementHandler = SystemMetaObject.forObject(handler);
        MappedStatement mappedStatement = (MappedStatement) statementHandler.getValue("delegate.mappedStatement");
        if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
            return invocation.proceed();
        }
        String namespace = mappedStatement.getId();
        String className = namespace.substring(0, namespace.lastIndexOf("."));
        Class<?> clazz = Class.forName(className);

        Tenant tenant = clazz.getAnnotation(Tenant.class);

        BoundSql boundSql = handler.getBoundSql();
        //获取sql
        String sql = boundSql.getSql();

        StringBuffer lastedSql = new StringBuffer();

        if (null != tenant) {
            JSONObject jsonObject = JSONUtil.createObj().append("tenant","1").append("customer","2");
            lastedSql.append(StrUtil.format("/** {} **/ ",jsonObject.toString())).append(sql);
            statementHandler.setValue("delegate.boundSql.sql", lastedSql.toString());
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target)
    {
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties)
    {

    }
}
